package controllers;

import java.util.List;

import javax.persistence.Query;

import play.data.validation.Required;
import play.db.jpa.JPA;

import models.ClubUser;
import models.Member;
import models.User;

import java.util.*;

import play.mvc.*;

import models.*;

public class Club extends ConnectedUser {

	public static void index() {
		listClubMembers(null);
	}

	public static void listClubMembers(String name) {
		User user = Application.connectedUser();
		if (user instanceof ClubUser) {
			List<Member> members = null;
			if (name == null || name.equals("")) {
				members = ((ClubUser) user).members;
			} else {
				Query query = JPA
						.em()
						.createQuery(
								"select m from Member m where upper(m.name) like :name and m.club = :club");
				query.setParameter("name", "%" + name.toUpperCase() + "%");
				query.setParameter("club", ((ClubUser) user));
				members = query.getResultList();
			}
			render(members);
		} else {
			flash.error("You are not a club!");
			render();
		}

	}

	public static void newMember() {
		render();
	}

	public static void saveMember(String name, String email, String home_town,
			String address, Date activation_end) {
		if (validation.hasErrors()) {
			flash.error("Please type again!");
			newMember();
		} else {
			User user = Application.connectedUser();
			if (user instanceof ClubUser) {
				ClubUser club = (ClubUser) user;
				club.addMember(name, email, home_town, address, activation_end);
				club.save();
				listClubMembers("");
			} else {
				flash.error("You are not a club!");
				newMember();
			}
		}
	}

	public static void editMember(Long id) {
		Member member = Member.findById(id);
		render(member);
	}

	public static void updateMember(Long id, String name, String email,
			String hometown, String address, Date activationEnds) {
		if (validation.hasErrors()) {
			flash.error("Please type again!");
			editMember(id);
		} else {
			User user = Application.connectedUser();
			if (user instanceof ClubUser) {
				Member member = Member.findById(id);
				member.name = name;
				member.email = email;
				member.hometown = hometown;
				member.address = address;
				member.activationEnds = activationEnds;
				member.save();
				listClubMembers("");
			} else {
				flash.error("You are not a club!");
				editMember(id);
			}
		}
	}

	public static void deleteMember(Long id) {
		Member member = Member.findById(id);
		member.delete();
		listClubMembers("");
	}

	public static void discounts() {
		renderDiscounts();
	}
}
